layui.use(['upload', 'table'], function() {
    var $ = layui.jquery
        , upload = layui.upload
        , table = layui.table;

    // 使用弹出层显示多文件上传页面
    function toUploadFilePage(){
        var index = layui.layer.open({
            title : "上传文件",
            type : 2,
            content : "/page/file/fileUpload",
            area: ['640px', '480px'],
            maxmin: true,
            success : function(layero, index){
                setTimeout(function(){
                    layui.layer.tips('点击此处返回文件列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            },
            cancel: function(index, layero) {
                tableIns.reload();
            }
        });
        //layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            index.render();
        })
    }

    // 弹出上传文件页面
    $(".uploadFile_btn").click(function(){
        toUploadFilePage();
    })

    // 刷新列表
    $(".refresh_btn").click(function(){
        tableIns.reload();
        layer.msg("刷新成功");
    })

    // 多文件列表
    var fileListView = $('#demoList')
        ,uploadListIns = upload.render({
        elem: '#testList'
        ,url: '/file/upload'
        ,accept: 'file'
        ,multiple: true
        ,auto: false
        ,bindAction: '#uploadAction'
        ,choose: function(obj){
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function(index, file, result){
                var tr = $(['<tr id="upload-'+ index +'">'
                    ,'<td>'+ file.name +'</td>'
                    ,'<td>'+ (file.size/1024).toFixed(1) +'kb</td>'
                    ,'<td>等待上传</td>'
                    ,'<td>'
                    ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    ,'</td>'
                    ,'</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function(){
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function(){
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                fileListView.append(tr);

                // 重新渲染下面表格宽高
            });
        }
        ,done: function(res, index, upload){
            if(res.code == 200){ //上传成功
                var tr = fileListView.find('tr#upload-'+ index)
                    ,tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
        ,error: function(index, upload){
            var tr = fileListView.find('tr#upload-'+ index)
                ,tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
        ,allDone: function(obj){ //当文件全部被提交后，才触发
            tableIns.reload();
        }
    });

    // 文件列表
    var tableIns = table.render({
        elem: '#fileList',
        url : '/file/list',
        cellMinWidth : 95,
        page : true,
        height : "full-120",
        limit : 10,
        limits : [10,15,20,25],
        id : "fileListTable",
        cols : [[
            {type: "checkbox", fixed:"left", width:50},
            {field: 'id', title: 'ID', width:60, align:"center", templet:function(d){
                return d.LAY_TABLE_INDEX+1;
            }},
            {field: 'fileName', title: '文件名称'},
            {field: 'size', title: '文件大小', width:250, align:'center', templet:function(d){
                return d.size + 'KB';
            }},
            {field: 'uploadTime', title: '上传时间', width:380, align:'center', templet:function(d){
                return d.uploadTime;
            }},
            {title: '操作', width:170, templet:'#fileListBar', fixed:"right", align:"center"}
        ]]
    });

    //列表操作
    table.on('tool(fileList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;

        if(layEvent === 'download'){ // 下载
            //window.open(data.url);
            location.href = data.url;
        } else if(layEvent === 'del'){ // 删除
            layer.confirm('确定删除此文件？',{icon:3, title:'提示信息'},function(index){
                $.get("/file/delete",{
                    fileIds : data.id  //将需要删除的Id作为参数传入
                },function(data){
                    layer.close(index);
                    var index2 = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                    setTimeout(function(){
                        layer.close(index2);
                        layer.msg("删除成功！");
                    },500);
                    tableIns.reload();
                })
            });
        }
    });

    // 搜索按钮
    $(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
            table.reload("fileListTable",{
                url: "/file/list",
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

})